<template>
  <div class="screen1-layout">
    <!-- 左侧一整列表格 -->
    <div class="left-panel">
      <ChartCard title="客户ID 销售数量的总和" class="data-table-card">
        <div class="table-container-wrapper">
          <table class="data-table">
            <thead>
              <tr>
                <th>客户ID</th>
                <th>销售数量的总和</th>
              </tr>
            </thead>
          </table>
          <div class="table-body-container scroll-container" ref="scrollContainer">
            <div class="scroll-content" ref="scrollContent">
              <table class="data-table">
                <tbody>
                  <tr v-for="(row, index) in customerIdData" :key="index">
                    <td>{{ row.customerId }}</td>
                    <td>{{ row.totalSales.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
          <table class="data-table">
            <tbody>
              <tr class="total-row">
                <td>总计</td>
                <td>{{ totalCustomerId.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </ChartCard>
    </div>

    <!-- 右侧上下布局 -->
    <div class="right-panel">
      <!-- 上方两个表格 -->
      <div class="top-tables">
        <ChartCard title="客户类型 销售数量的总和" class="data-table-card">
          <div class="table-container">
            <table class="data-table">
              <thead>
                <tr>
                  <th>客户类型</th>
                  <th>销售数量的总和</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(row, index) in customerTypeData" :key="index">
                  <td>{{ row.customerType }}</td>
                  <td>{{ row.totalSales.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) }}</td>
                </tr>
                <tr class="total-row">
                  <td>总计</td>
                  <td>{{ totalCustomerType.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </ChartCard>

        <ChartCard title="产品类别 销售数量的总和" class="data-table-card">
          <div class="table-container">
            <table class="data-table">
              <thead>
                <tr>
                  <th>产品类别</th>
                  <th>销售数量的总和</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(row, index) in productCategoryData" :key="index">
                  <td>{{ row.productCategory }}</td>
                  <td>{{ row.totalSales.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) }}</td>
                </tr>
                <tr class="total-row">
                  <td>总计</td>
                  <td>{{ totalProductCategory.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </ChartCard>
      </div>

      <!-- 下方两个统计图 -->
      <div class="bottom-charts">
        <ChartCard title="销售数量的总和(按客户类型)">
          <ECharts :option="customerTypePieOption" />
        </ChartCard>
        <ChartCard title="销售数量的总和(按药品名称)">
          <ECharts :option="drugNameBarOption" />
        </ChartCard>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted, nextTick } from 'vue'
import ChartCard from '../components/ChartCard.vue'
import ECharts from '../components/ECharts.vue'
import { generateRandomData, getBarOption, getLineOption, getPieOption } from '../utils/chartOptions'
import * as echarts from 'echarts'
import './Screen.css'
import { 
  getCustomerIdSalesData, 
  getCustomerTypeSalesData, 
  getProductCategorySalesData,
  getCustomerTypePieData,
  getDrugNameBarData
} from '../api/screen1'

// 滚动容器引用
const scrollContainer = ref(null)
const scrollContent = ref(null)
const isScrolling = ref(false)
const isUserScrolling = ref(false)
let scrollAnimationId = null
let isTouching = false
let isAutoScrolling = false
let lastScrollTop = 0

// 表格数据
const customerIdData = ref([])
const customerTypeData = ref([])
const productCategoryData = ref([])

// 加载状态
const loading = ref(false)

// 只计算原始数据的总和，不包含重复的循环滚动数据
const totalCustomerId = computed(() => {
  if (!customerIdData.value || customerIdData.value.length === 0) return 0
  return customerIdData.value.reduce((sum, row) => sum + (row.totalSales || 0), 0)
})
const totalCustomerType = computed(() => {
  if (!customerTypeData.value || customerTypeData.value.length === 0) return 0
  return customerTypeData.value.reduce((sum, row) => sum + (row.totalSales || 0), 0)
})
const totalProductCategory = computed(() => {
  if (!productCategoryData.value || productCategoryData.value.length === 0) return 0
  return productCategoryData.value.reduce((sum, row) => sum + (row.totalSales || 0), 0)
})

// 图表配置
const customerTypePieOption = ref({})
const drugNameBarOption = ref({})
const barOption = ref({})
const lineOption = ref({})
const pieOption = ref({})
const performanceOption = ref({})

// 自动滚动函数
const startAutoScroll = () => {
  if (!scrollContainer.value || isUserScrolling.value || isTouching || isAutoScrolling) {
    return
  }
  
  const container = scrollContainer.value
  const content = scrollContent.value
  if (!container || !content) return
  
  stopAutoScroll() // 先停止之前的滚动
  isAutoScrolling = true
  lastScrollTop = container.scrollTop
  
  let currentScroll = container.scrollTop
  let lastTime = performance.now()
  let isAtBottom = false
  
  const scroll = (currentTime) => {
    if (isUserScrolling.value || isTouching || !container || !isAutoScrolling) {
      isAutoScrolling = false
      isAtBottom = false
      return
    }
    
    // 重新计算最大滚动位置（因为内容可能会变化）
    const contentHeight = content.scrollHeight
    const containerHeight = container.clientHeight
    const maxScrollTop = Math.max(0, contentHeight - containerHeight)
    
    // 如果内容高度小于容器高度，不需要滚动
    if (maxScrollTop <= 0) {
      isAutoScrolling = false
      isAtBottom = false
      return
    }
    
    // 如果已经到达底部，等待后重置
    if (isAtBottom) {
      return
    }
    
    const deltaTime = currentTime - lastTime
    lastTime = currentTime
    
    // 计算滚动速度，每16ms（约60fps）滚动1像素
    const scrollSpeed = 0.8 // 像素/帧，可调整速度
    currentScroll += scrollSpeed * (deltaTime / 16)
    
    // 如果滚动到末尾，重置到顶部
    if (currentScroll >= maxScrollTop) {
      // 滚动到末尾
      currentScroll = maxScrollTop
      container.scrollTop = maxScrollTop
      lastScrollTop = maxScrollTop
      isAtBottom = true
      
      // 短暂停留后重置到顶部
      setTimeout(() => {
        if (!isUserScrolling.value && !isTouching && isAutoScrolling && container) {
          currentScroll = 0
          container.scrollTop = 0
          lastScrollTop = 0
          isAtBottom = false
          lastTime = performance.now() // 重置时间，确保滚动速度正常
          // 继续滚动
          scrollAnimationId = requestAnimationFrame(scroll)
        } else {
          isAutoScrolling = false
          isAtBottom = false
        }
      }, 1000) // 停留500ms
    } else {
      container.scrollTop = currentScroll
      lastScrollTop = currentScroll
      scrollAnimationId = requestAnimationFrame(scroll)
    }
  }
  
  scrollAnimationId = requestAnimationFrame(scroll)
}

const stopAutoScroll = () => {
  isAutoScrolling = false
  if (scrollAnimationId) {
    cancelAnimationFrame(scrollAnimationId)
    scrollAnimationId = null
  }
}

// 触摸事件处理
const handleTouchStart = (e) => {
  isTouching = true
  isUserScrolling.value = true
  stopAutoScroll()
  if (scrollContainer.value) {
    lastScrollTop = scrollContainer.value.scrollTop
  }
}

const handleTouchMove = (e) => {
  // 触摸移动时保持停止自动滚动状态
  if (scrollContainer.value) {
    const currentScrollTop = scrollContainer.value.scrollTop
    // 如果滚动位置发生变化，说明用户在滚动
    if (Math.abs(currentScrollTop - lastScrollTop) > 1) {
      isUserScrolling.value = true
      stopAutoScroll()
      lastScrollTop = currentScrollTop
    }
  }
}

const handleTouchEnd = () => {
  isTouching = false
  // 延迟恢复自动滚动，给用户一点时间
  const timer = setTimeout(() => {
    if (!isTouching) {
      isUserScrolling.value = false
      // 重新记录当前位置
      if (scrollContainer.value) {
        lastScrollTop = scrollContainer.value.scrollTop
      }
      startAutoScroll()
    }
  }, 2000)
  // 保存timer以便清理
  if (!window.touchResetTimers) {
    window.touchResetTimers = []
  }
  window.touchResetTimers.push(timer)
}

// 鼠标滚轮和手动滚动处理
const handleWheel = () => {
  // 用户滚轮操作时暂停自动滚动
  isUserScrolling.value = true
  stopAutoScroll()
  clearTimeout(window.scrollResetTimer)
  window.scrollResetTimer = setTimeout(() => {
    isUserScrolling.value = false
    if (scrollContainer.value) {
      lastScrollTop = scrollContainer.value.scrollTop
    }
    startAutoScroll()
  }, 2000)
}

const handleScroll = () => {
  if (!scrollContainer.value) return
  
  const currentScrollTop = scrollContainer.value.scrollTop
  const scrollDelta = Math.abs(currentScrollTop - lastScrollTop)
  
  // 只有当滚动距离大于阈值时才认为是用户手动滚动
  // 这样可以避免自动滚动触发此事件
  if (scrollDelta > 2 && !isAutoScrolling) {
    isUserScrolling.value = true
    stopAutoScroll()
  }
  
  // 更新最后滚动位置
  lastScrollTop = currentScrollTop
  
  clearTimeout(window.scrollResetTimer)
  window.scrollResetTimer = setTimeout(() => {
    if (!isUserScrolling.value && !isTouching) {
      startAutoScroll()
    }
  }, 2000)
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 并行请求所有数据
    const [
      customerIdRes,
      customerTypeRes,
      productCategoryRes,
      pieDataRes,
      barDataRes
    ] = await Promise.all([
      getCustomerIdSalesData(),
      getCustomerTypeSalesData(),
      getProductCategorySalesData(),
      getCustomerTypePieData(),
      getDrugNameBarData()
    ])

    // 更新表格数据
    customerIdData.value = customerIdRes || []
    customerTypeData.value = customerTypeRes || []
    productCategoryData.value = productCategoryRes || []

    // 更新客户类型饼图
    if (pieDataRes) {
      customerTypePieOption.value = {
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          textStyle: { color: '#fff' },
          data: pieDataRes.legend || pieDataRes.data?.map(item => item.name) || []
        },
        series: [
          {
            name: '销售数量',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#0a0e27',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: function(params) {
                return params.name + '\n' + (params.value / 1000000).toFixed(2) + '百万\n(' + params.percent + '%)'
              },
              color: '#fff'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 16,
                fontWeight: 'bold'
              }
            },
            data: pieDataRes.data || pieDataRes
          }
        ]
      }
    }

    // 更新药品名称柱状图
    if (barDataRes) {
      const drugNames = barDataRes.names || barDataRes.data?.map(item => item.name) || []
      const drugSalesData = barDataRes.values || barDataRes.data?.map(item => item.value) || []
      
      drugNameBarOption.value = {
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' }
        },
        grid: {
          left: '15%',
          right: '10%',
          top: '10%',
          bottom: '15%'
        },
        xAxis: {
          type: 'category',
          data: drugNames,
          axisLine: { lineStyle: { color: '#1890ff' } },
          axisLabel: { color: '#fff', rotate: 45 }
        },
        yAxis: {
          type: 'value',
          name: '销售数量的总和',
          max: Math.max(...drugSalesData) * 1.2 || 60000000,
          axisLine: { lineStyle: { color: '#1890ff' } },
          axisLabel: { 
            color: '#fff',
            formatter: function(value) {
              return (value / 1000000).toFixed(0) + ' 百万'
            }
          },
          splitLine: { lineStyle: { color: 'rgba(24, 144, 255, 0.1)' } }
        },
        series: [
          {
            name: '销售数量',
            type: 'bar',
            data: drugSalesData,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#36cfc9' },
                { offset: 1, color: '#1890ff' }
              ])
            },
            label: {
              show: true,
              position: 'top',
              color: '#fff',
              formatter: function(params) {
                return (params.value / 1000000).toFixed(1) + 'M'
              }
            }
          }
        ]
      }
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    // 可以在这里显示错误提示
    // ElMessage.error('数据加载失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  // 加载数据
  await loadData()

  // 右侧图表
  const categories = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
  
  const barData = {
    categories,
    series: [{
      name: '销售额',
      data: generateRandomData(7).data
    }]
  }
  
  const lineData = {
    categories,
    series: [{
      name: '访问量',
      data: generateRandomData(7).data
    }]
  }
  
  const pieData = {
    name: '数据分布',
    data: [
      { value: 335, name: '类别A' },
      { value: 310, name: '类别B' },
      { value: 234, name: '类别C' },
      { value: 135, name: '类别D' },
      { value: 154, name: '类别E' }
    ]
  }

  barOption.value = getBarOption(barData)
  lineOption.value = getLineOption(lineData)
  pieOption.value = getPieOption(pieData)
  
  performanceOption.value = getBarOption({
    categories: ['CPU', '内存', '磁盘', '网络'],
    series: [{
      name: '使用率',
      data: [65, 78, 45, 32]
    }]
  })

  // 使用 nextTick 确保 DOM 已渲染
  nextTick(() => {
    if (scrollContainer.value) {
      scrollContainer.value.addEventListener('touchstart', handleTouchStart, { passive: true })
      scrollContainer.value.addEventListener('touchmove', handleTouchMove, { passive: true })
      scrollContainer.value.addEventListener('touchend', handleTouchEnd, { passive: true })
      scrollContainer.value.addEventListener('touchcancel', handleTouchEnd, { passive: true })
      scrollContainer.value.addEventListener('wheel', handleWheel, { passive: true })
      scrollContainer.value.addEventListener('scroll', handleScroll, { passive: true })
      
      // 初始化最后滚动位置
      lastScrollTop = scrollContainer.value.scrollTop
      
      // 延迟启动自动滚动，确保 DOM 已完全渲染
      setTimeout(() => {
        startAutoScroll()
      }, 1000)
    }
  })
})

onUnmounted(() => {
  stopAutoScroll()
  if (scrollContainer.value) {
    scrollContainer.value.removeEventListener('touchstart', handleTouchStart)
    scrollContainer.value.removeEventListener('touchmove', handleTouchMove)
    scrollContainer.value.removeEventListener('touchend', handleTouchEnd)
    scrollContainer.value.removeEventListener('touchcancel', handleTouchEnd)
    scrollContainer.value.removeEventListener('wheel', handleWheel)
    scrollContainer.value.removeEventListener('scroll', handleScroll)
  }
  if (window.scrollResetTimer) {
    clearTimeout(window.scrollResetTimer)
  }
  // 清理所有触摸重置定时器
  if (window.touchResetTimers) {
    window.touchResetTimers.forEach(timer => clearTimeout(timer))
    window.touchResetTimers = []
  }
})
</script>

<style scoped>
.screen1-layout {
  display: flex;
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, #0a0e27 0%, #1a1f3a 100%);
  color: #fff;
  overflow: hidden;
  padding: 15px;
  gap: 15px;
}

.left-panel {
  width: 25%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.data-table-card {
  flex: 1;
  min-height: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.table-container-wrapper {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
  height: 100%;
}

.table-container-wrapper > .data-table:first-child {
  flex-shrink: 0;
  margin-bottom: 0;
  width: 100%;
}

.table-body-container {
  flex: 1;
  min-height: 0;
  overflow: visible;
  position: relative;
  margin-bottom: 0;
}

.table-body-container table {
  width: 100%;
}

.scroll-container {
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  position: relative;
  scroll-behavior: auto;
  -webkit-overflow-scrolling: touch;
  /* 隐藏滚动条但保持滚动功能 */
  scrollbar-width: thin;
  scrollbar-color: rgba(24, 144, 255, 0.5) rgba(255, 255, 255, 0.05);
}

.scroll-container::-webkit-scrollbar {
  width: 6px;
}

.scroll-container::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 3px;
}

.scroll-container::-webkit-scrollbar-thumb {
  background: rgba(24, 144, 255, 0.5);
  border-radius: 3px;
}

.scroll-container::-webkit-scrollbar-thumb:hover {
  background: rgba(24, 144, 255, 0.8);
}

.scroll-content {
  will-change: transform;
}

.table-container-wrapper > .data-table:last-child {
  flex-shrink: 0;
  margin-top: auto;
  border-top: 2px solid rgba(24, 144, 255, 0.4);
  width: 100%;
  background: rgba(24, 144, 255, 0.1);
}

.table-container-wrapper > .data-table:last-child tbody {
  display: table-row-group;
}

.table-container-wrapper > .data-table:last-child tbody tr {
  display: table-row;
}

/* 确保表格内容完整显示 */
.scroll-content table {
  margin: 0;
  padding: 0;
  width: 100%;
}

.table-container::-webkit-scrollbar {
  width: 6px;
}

.table-container::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 3px;
}

.table-container::-webkit-scrollbar-thumb {
  background: rgba(24, 144, 255, 0.5);
  border-radius: 3px;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 12px;
  table-layout: fixed;
  border-spacing: 0;
}

.data-table thead {
  background: rgba(24, 144, 255, 0.3);
  backdrop-filter: blur(5px);
}

.table-container-wrapper > .data-table:first-child thead {
  position: sticky;
  top: 0;
  z-index: 10;
}

.data-table th,
.data-table td {
  padding: 8px 10px;
  text-align: left;
  border-bottom: 1px solid rgba(24, 144, 255, 0.2);
  color: #fff;
}

.data-table th:first-child,
.data-table td:first-child {
  width: 40%;
}

.data-table th:last-child,
.data-table td:last-child {
  width: 60%;
  text-align: right;
}

.data-table tbody tr:hover {
  background: rgba(24, 144, 255, 0.1);
}

.data-table th {
  font-weight: bold;
  color: #36cfc9;
}

.total-row {
  background: rgba(24, 144, 255, 0.25) !important;
  font-weight: bold;
  color: #36cfc9 !important;
  font-size: 13px;
}

.table-container-wrapper > .data-table:last-child .total-row {
  background: rgba(24, 144, 255, 0.3) !important;
  border-top: 1px solid rgba(54, 207, 201, 0.4);
}

.table-container-wrapper > .data-table:last-child .total-row td {
  padding: 12px 10px;
  height: auto;
  font-size: 13px;
  font-weight: bold;
}

.table-container-wrapper > .data-table:last-child .total-row td:first-child {
  width: 40%;
}

.table-container-wrapper > .data-table:last-child .total-row td:last-child {
  width: 60%;
  text-align: right;
}

.right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
  gap: 15px;
}

.top-tables {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
  height: 40%;
  flex-shrink: 0;
  overflow: hidden;
}

.bottom-charts {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
  flex: 1;
  min-height: 0;
  overflow: hidden;
}
</style>
